package com.esunny.online.controller.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.esunny.online.domain.entity.User;
import com.esunny.online.util.HostHolder;
import com.esunny.online.util.JwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author ：李先生
 * @date ：Created in 2020/7/19 16:18
 * @description： 身份令牌拦截器
 * @modified By：
 * @version: $
 */
@Component
public class LoginTicketInterceptor implements HandlerInterceptor {
    @Resource
    private HostHolder hostHolder;

    private Logger logger = LoggerFactory.getLogger(LoginTicketInterceptor.class);

    /**
     * 前置拦截
     *
     * @param request  http请求
     * @param response http相应
     * @param handler  处理器
     * @return 是否
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        if (responseOptionsRequest(request, response)) {
            return true;
        }

        String headerTicket = request.getHeader("ticket");
        logger.info("headerTicket：" + headerTicket);

        //进行令牌判断
        if ( StringUtils.isNotEmpty(headerTicket)) {
            User user = JwtUtil.parseJwtToUser(headerTicket);
            logger.info("拦截器User："+user);
            if (user != null) {
                hostHolder.setUser(user);
                return true;
            }
        }
        //response返回信息
        response.setStatus(400);
        response.setContentType("application/json; charset=UTF-8");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 400);
        jsonObject.put("msg", "尚未登录，请登录后操作");

        PrintWriter writer;
        try {
            writer = response.getWriter();
            writer.write(jsonObject.toJSONString());
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * Controller请求完成，删除数据
     *
     * @param request  http请求
     * @param response http相应
     * @param handler  处理器
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        hostHolder.clear();
    }

    /**
     * 整个请求完成，清除数据
     *
     * @param request  http请求
     * @param response http相应
     * @param handler  处理器
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        hostHolder.clear();//清除数据
    }

    /**
     * @param request 请求
     * @param response 相应
     * @return 布尔值
     * @throws IOException 报错
     */
    private static boolean responseOptionsRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Headers", "ticket,Origin,Content-Type,Accept,token,X-Requested-With");
        if (request.getMethod().equals(HttpMethod.OPTIONS.toString())) {
            response.setStatus(HttpStatus.OK.value());
            response.getWriter().write("OPTIONS returns OK");
            return true;
        } else {
            return false;
        }
    }

}
